import time

from rest_framework import serializers
from django.db.models import F, Q
from goods.models import Goods
from utils.alipay import AliPay
from .models import ShoppingCart, OrderInfo, OrderGoods
from goods.serializers import GoodsSerializer


class OrderGoodsSerializer(serializers.ModelSerializer):
    goods = GoodsSerializer(many=False)
    class Meta:
        model = OrderGoods
        fields = '__all__'


class OrderDetailSerializer(serializers.ModelSerializer):
    goods = OrderGoodsSerializer(many=True)
    alipay_url = serializers.SerializerMethodField(read_only=True)

    def get_alipay_url(self, obj):
        alipay = AliPay()
        url = alipay.direct_pay(
            subject=obj.order_sn,
            out_trade_no=obj.order_sn,
            total_amount=obj.order_amount,
        )
        re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(
            data=url)
        return re_url

    class Meta:
        model = OrderInfo
        fields = '__all__'


class OrderSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    order_sn = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    pay_status = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    alipay_url = serializers.SerializerMethodField(read_only=True)

    def get_alipay_url(self, obj):
        alipay = AliPay()
        url = alipay.direct_pay(
            subject=obj.order_sn,
            out_trade_no=obj.order_sn,
            total_amount=obj.order_amount,
        )
        re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(
            data=url)
        return re_url

    def generate_order_sn(self):
        from random import Random
        rand_num = Random().randint(10, 99)
        order_sn = f"{time.strftime('%Y%m%d%H%M')}{self.context['request'].user.id}{rand_num}"
        return order_sn

    def validate(self, attrs):
        attrs['order_sn'] = self.generate_order_sn()
        return attrs

    class Meta:
        model = OrderInfo
        fields = '__all__'


class ShoppingCartDetailSerializer(serializers.ModelSerializer):
    goods = GoodsSerializer()
    class Meta:
        model = ShoppingCart
        fields = '__all__'


class ShoppingCartSerializer(serializers.Serializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    nums = serializers.IntegerField(required=True, min_value=1,
                                    error_messages={
                                        "required": "商品数量不能为空",
                                        "min_value": "商品数量不能小于1",
                                    })
    goods = serializers.PrimaryKeyRelatedField(queryset=Goods.objects.all(),
                                               required=True)

    def update(self, instance, validated_data):
        instance.nums = validated_data.get("nums")
        instance.save()
        return instance

    def create(self, validated_data):
        # 查找购物车实例，如果不存在则创建一个新的
        user = self.context["request"].user
        goods = validated_data.get("goods")
        # 获取购物车实例
        cart, created = ShoppingCart.objects.get_or_create(user=user, goods=goods)
        if created:
            print("加入购物车成功")
        else:
            print("更新购物车成功")

        # 更新购物车中的商品数量
        nums = validated_data.get("nums")
        cart.nums += nums
        cart.save()

        return cart

    # def create(self, validated_data):
    #     user = self.context["request"].user
    #     nums = validated_data.get("nums")
    #     goods = validated_data.get("goods")
    #     exist_cart = ShoppingCart.objects.filter(user=user, goods=goods)
    #     if exist_cart:
    #         exist_cart = exist_cart[0]
    #         exist_cart.nums += nums
    #         exist_cart.save()
    #     else:
    #         # ShoppingCart.objects.create(user=user, nums=nums, goods=goods)
    #         exist_cart = ShoppingCart.objects.create(**validated_data)
    #     return exist_cart

    # def create(self, validated_data):
        #     # 查找购物车实例，如果不存在则创建一个新的
        #     user = self.context["request"].user
        #     nums = validated_data.get("nums")
        #     goods = validated_data.get("goods")
        #     # Retrieve the current value of 'nums' from the database
        #     current_nums = ShoppingCart.objects.filter(user=user, goods=goods). \
        #                    values_list('nums', flat=False).first() or (0,)
        #
        #     # Perform the addition operation
        #     new_nums = current_nums[0] + nums
        #     cart, created = ShoppingCart.objects.update_or_create(
        #         user=user,
        #         goods=goods,
        #         defaults={
        #             'nums': new_nums,
        #             'add_time': datetime.now(),
        #         },
        #     )
        #     if created:
        #         print("加入购物车成功")
        #     else:
        #         print("更新购物车成功")
        #
        #     return cart